package cn.yuanqiao.system.service.impl;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.core.domain.entity.DeptTreeSelect;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.yuanqiao.common.annotation.DataScope;
import cn.yuanqiao.common.constant.UserConstants;
import cn.yuanqiao.common.core.domain.TreeSelect;
import cn.yuanqiao.common.core.domain.entity.SysDept;
import cn.yuanqiao.common.core.domain.entity.SysRole;
import cn.yuanqiao.common.core.domain.entity.SysUser;
import cn.yuanqiao.common.core.text.Convert;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.spring.SpringUtils;
import cn.yuanqiao.system.mapper.SysDeptMapper;
import cn.yuanqiao.system.mapper.SysRoleMapper;
import cn.yuanqiao.system.service.ISysDeptService;

/**
 * 部门管理 服务实现
 *
 * @author ruoyi
 */
@Service
public class SysDeptServiceImpl implements ISysDeptService {
    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d", deptColumn = "dept_id", userColumn = "user_id")
    public List<SysDept> selectDeptList(SysDept dept) {
        dept.setTenantCode(SecurityUtils.getTenantCode());
        return deptMapper.selectDeptList(dept);
    }


    /**
     * 查询部门树结构信息
     *
     * @param dept 部门信息
     * @return 部门树信息集合
     */
    @Override
    public List<TreeSelect> selectDeptTreeList(SysDept dept) {
        dept.setStatus("0");
        List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
        return buildDeptTreeSelect(depts);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = depts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
        for (SysDept dept : depts) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts) {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    public List<DeptTreeSelect> deptTreeSelect(List<SysDept> depts) {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(DeptTreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Long> selectDeptListByRoleId(Long roleId) {
        SysRole role = roleMapper.selectRoleById(roleId);
        return deptMapper.selectDeptListByRoleId(roleId, role.isDeptCheckStrictly());
    }


    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public SysDept selectDeptById(Long deptId) {
        return deptMapper.selectDeptById(deptId);
    }

    @Override
    public SysDept selectDeptByName(String deptName, String tenantCode) {
        return deptMapper.selectDeptByName(deptName, tenantCode);
    }

    @Override
    public List<SysDept> selectDeptListByDeptName(SysDept sysDept) {
        return deptMapper.selectDeptListByDeptName(sysDept.getDeptName(), sysDept.getTenantCode());
    }


    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId) {
        return deptMapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 是否存在子节点
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Long deptId) {
        int result = deptMapper.hasChildByDeptId(deptId);
        return result > 0;
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId) {
        int result = deptMapper.checkDeptExistUser(deptId);
        return result > 0;
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public boolean checkDeptNameUnique(SysDept dept) {
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId(), SecurityUtils.getTenantCode());
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }

        SysDept infocode = deptMapper.selectDeptByCode(dept.getDeptCode(),SecurityUtils.getTenantCode());
        if (StringUtils.isNotNull(infocode)&& infocode.getDeptId().longValue() != deptId.longValue() ) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
    /**
     * 校验部门是否有数据权限
     *
     * @param deptId 部门id
     */
    @Override
    public void checkDeptDataScope(Long deptId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysDept dept = new SysDept();
            dept.setDeptId(deptId);
            List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
            if (StringUtils.isEmpty(depts)) {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int insertDept(SysDept dept) {
        SysDept info = deptMapper.selectDeptById(dept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new ServiceException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        dept.setDeptId(SnowflakeIdGenerator.generateId());
        dept.setTenantCode(SecurityUtils.getTenantCode());
        return deptMapper.insertDept(dept);
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int updateDept(SysDept dept) {
        SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
        SysDept oldDept = deptMapper.selectDeptById(dept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = deptMapper.updateDept(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
                && !StringUtils.equals("0", dept.getAncestors())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(SysDept dept) {
        String ancestors = dept.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        deptMapper.updateDeptStatusNormal(deptIds);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = deptMapper.selectChildrenDeptById(deptId);
        for (SysDept child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            deptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Long deptId) {
        return deptMapper.deleteDeptById(deptId);
    }

    @Override
    public R<SysDept> addAsync(SysDept sysDept) {
        if (!checkDeptNameUnique(sysDept)) {
            return R.fail("新增部门'" + sysDept.getDeptName() + "'失败，部门名称已存在");
        }
        insertDept(sysDept);
        return R.ok(sysDept);
    }

    @Override
    public R<Integer> editAsync(SysDept sysDept) {
        Long deptId = sysDept.getDeptId();
        checkDeptDataScope(deptId);
        if (!checkDeptNameUnique(sysDept)) {
            return R.fail("修改部门'" + sysDept.getDeptName() + "'失败，部门名称已存在");
        } else if (sysDept.getParentId().equals(deptId)) {
            return R.fail("修改部门'" + sysDept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, sysDept.getStatus()) && selectNormalChildrenDeptById(deptId) > 0) {
            return R.fail("该部门包含未停用的子部门！");
        }
        return R.ok(updateDept(sysDept));
    }

    @Override
    public R<Integer> removeAsync(Long deptId) {
        if (hasChildByDeptId(deptId)) {
            return R.fail("存在下级部门,不允许删除");
        }
        if (checkDeptExistUser(deptId)) {
            return R.fail("部门存在用户,不允许删除");
        }
        checkDeptDataScope(deptId);
        return R.ok(deleteDeptById(deptId));
    }

    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<TreeSelect> selectDeptUserTreeList(SysDept dept) {
        List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
        SysUser sysUser = new SysUser();
        sysUser.setTenantCode(SecurityUtils.getTenantCode());
        List<SysUser> sysUsers = sysUserMapper.selectUserList(sysUser);
        return buildDeptUserTreeSelect(depts, sysUsers);
    }

    @Override
    public List<TreeSelect> selectDeptUserTreeListNoDateScope(SysDept dept) {
        List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptListNoDateScope(dept);
        SysUser sysUser = new SysUser();
        sysUser.setTenantCode(SecurityUtils.getTenantCode());
        List<SysUser> sysUsers = sysUserMapper.selectUserList(sysUser);
        return buildDeptUserTreeSelect(depts, sysUsers);
    }

    @Override
    public List<DeptTreeSelect> synchronizationDeptTreeList(SysDept dept) {
        List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptLists(dept);
        return deptTreeSelect(depts);
    }


    @Override
    public List<TreeSelect> deptTreeNoDateScope(SysDept dept) {
        dept.setStatus("0");
        List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptListNoDateScope(dept);
        return buildDeptTreeSelect(depts);
    }
    @Override
    public String importDept(List<SysDept> list) {
        StringBuilder erro = new StringBuilder();
        int i = 0;
        for (SysDept sysDept : list) {
            i++;
            if(sysDept == null){
                continue;
            }
            if(StringUtils.isEmpty(sysDept.getDeptCode())&&StringUtils.isEmpty(sysDept.getDeptName())&&StringUtils.isEmpty(sysDept.getParentCode()))
            {
                erro.append("第"+i+"新增部门'" + sysDept.getDeptName() + "'失败，必填项为空，请检查数据。;");
                continue;
            }
            if (!checkDeptNameUnique(sysDept)) {
                erro.append("第"+i+"新增部门'" + sysDept.getDeptName() + "'失败，部门名称已存在。;");
                continue;
            }
            sysDept.setParentName("集团组织架构");
            sysDept.setStatus("0");
            sysDept.setAncestors("0");
            sysDept.setParentId(100L);
            SysDept info = deptMapper.selectDeptByCode(sysDept.getParentCode(), SecurityUtils.getTenantCode().toUpperCase());
            // 如果父节点不为正常状态,则不允许新增子节点
            if (info != null) {
                sysDept.setStatus(info.getStatus());
                sysDept.setAncestors(info.getAncestors() + "," + info.getDeptId());
                sysDept.setParentId(info.getDeptId());
                sysDept.setParentName(info.getDeptName());
            }
            sysDept.setDeptId(SnowflakeIdGenerator.generateId());
            sysDept.setTenantCode(SecurityUtils.getTenantCode());
            sysDept.setDelFlag("0");
            sysDept.setCreateBy(SecurityUtils.getUsername());
            sysDept.setCreateTime(new Date());
            deptMapper.insertDept(sysDept);

        }
        return org.apache.commons.lang3.StringUtils.isNotBlank(erro) ? erro.toString() : "导入新增部门成功。;";
    }

    public List<SysDept> selectDeptListNoDateScope(SysDept dept) {
        dept.setTenantCode(SecurityUtils.getTenantCode());
        return deptMapper.selectDeptListNoDateScope(dept);
    }

    public List<SysDept> selectDeptLists(SysDept dept) {
        /*  dept.setStatus("0");*/

        return deptMapper.selectDeptLists(dept);
    }

    private List<TreeSelect> buildDeptUserTreeSelect(List<SysDept> depts, List<SysUser> users) {
        List<SysDept> deptTrees = buildDeptUserTree(depts, users);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    private List<SysDept> buildDeptUserTree(List<SysDept> depts, List<SysUser> users) {
        List<SysDept> returnList = new ArrayList<>();
        Map<Long, List<SysUser>> userMap = users.stream()
                .collect(Collectors.groupingBy(SysUser::getDeptId));

        for (SysDept dept : depts) {
            List<SysUser> deptUsers = userMap.get(dept.getDeptId());
            if (deptUsers != null) {
                dept.getUserChildren().addAll(deptUsers);
            }

            // 如果是顶级节点，遍历该父节点的所有子节点
            if (dept.getParentId() == null || dept.getParentId() == 0L) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }

        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t) {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext()) {
            SysDept n = it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t) {
        return getChildList(list, t).size() > 0;
    }


    public Integer syncDeptByOA(String tenantCode){
        SysDept query = new SysDept();
        query.setTenantCode(tenantCode);
        List<SysDept> oaDepts = deptMapper.selectDeptListOther(query);
        List<SysDept> sysDepts = deptMapper.selectDeptList(query);
        Map<String, SysDept> sysDeptsMap = sysDepts.stream()
                .filter(dept -> dept.getOneId() != null)  // 过滤掉 oneId 为 null 的元素
                .collect(Collectors.toMap(SysDept::getOneId, Function.identity()));
        //对比两个list集合，将sysUsers1中不存在但是susUsers中存在的数据进行更新，以oneId为唯一对比字段
        List<SysDept> oaDeptsTree = buildDeptTreeOA(oaDepts);
        // 递归遍历 oaDeptsTree，检查 sysDepts 中是否存在相同的 oneId
        compareDept(oaDeptsTree, sysDeptsMap,tenantCode);
        return 0;
    }

    //递归遍历List<SysDept>，对比每个节点的oneId在 Map<String, SysDept>中是否存在
    private void compareDept(List<SysDept> oaDeptList, Map<String, SysDept> sysDeptMap,String tenantCode) {
        for (SysDept oaDept : oaDeptList) {
            SysDept sysDept = sysDeptMap.get(oaDept.getOneId());
            if (sysDept != null){
                // 如果 sysUsersMap 中存在相同的 oneId，则更新 sysUsers 中的数据
                oaDept.setTenantCode(tenantCode);
                SysDept parentDept = deptMapper.selectDeptByOneId(oaDept.getOneParentId());
                if (parentDept != null){
                    oaDept.setParentId(parentDept.getDeptId());
                    oaDept.setAncestors(parentDept.getAncestors()+","+parentDept.getDeptId());
                }else {
                    oaDept.setParentId(100L);
                    oaDept.setAncestors("0,100");
                }
                deptMapper.updateDeptByOneId(oaDept);
            }else {
                // 如果 sysUsersMap 中不存在相同的 oneId，则进行插入
                oaDept.setTenantCode(tenantCode);
                SysDept parentDept = deptMapper.selectDeptByOneId(oaDept.getOneParentId());
                oaDept.setDeptId(SnowflakeIdGenerator.generateId());
                if (parentDept != null){
                    oaDept.setParentId(parentDept.getDeptId());
                    oaDept.setAncestors(parentDept.getAncestors()+","+parentDept.getDeptId());
                }else {
                    oaDept.setParentId(100L);
                    oaDept.setAncestors("0,100");
                }
                deptMapper.insertDept(oaDept);
            }
            if (oaDept.getChildren() != null && !oaDept.getChildren().isEmpty()){
                compareDept(oaDept.getChildren(), sysDeptMap,tenantCode);
            }
        }
    }


    public List<SysDept> buildDeptTreeOA(List<SysDept> depts) {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<String> tempList = depts.stream().map(SysDept::getOneId).collect(Collectors.toList());
        for (SysDept dept : depts) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getOneParentId())) {
                recursionFnOA(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }


    /**
     * 递归列表
     */
    private void recursionFnOA(List<SysDept> list, SysDept t) {
        // 得到子节点列表
        List<SysDept> childList = getChildListOA(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList) {
            if (hasChildOA(list, tChild)) {
                recursionFnOA(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildListOA(List<SysDept> list, SysDept t) {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext()) {
            SysDept n = it.next();
            if (StringUtils.isNotNull(n.getOneParentId()) && n.getOneParentId().equals(t.getOneId())) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChildOA(List<SysDept> list, SysDept t) {
        return getChildListOA(list, t).size() > 0;
    }

}
